/**
 * Created by ren on 05/04/2017.
 */
'use strict';
import React, {Component} from 'react';
import {
  Platform,
  StatusBar,
  View,
  Image,
  ScrollView,
  RefreshControl,
  ActivityIndicator,
  ListView,
  Modal,
  TouchableWithoutFeedback
} from 'react-native';
import {Text, ListItem, Body, Button, Container, Header, Left, Icon, Title, Right} from 'native-base'
import {getSize} from '../../utils/response'
import * as api from '../../utils/api'
import * as netservice from '../../utils/netservice'
import PullToRefreshListView from 'react-native-smart-pull-to-refresh-listview'
import {connect} from 'react-redux'
import PageUtil from '../../utils/PageUtil';
import OrderDetail2 from '../OrderDetail2'
import NotRecord from '../../components/NotRecord'
let timer1 = '',
  timer2 = ''
class OrderList extends Component {
  constructor(props) {
    super(props);
    this.PageUtil = new PageUtil();
    // 初始状态
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    let dataList = []
    this.state = {
      pageIndex: 1,
      dataList: dataList,
      total: 1,
      dataSource: ds.cloneWithRows(dataList),
      modalVisible: true,
      isToNextPage: true
    };
  }

  componentDidMount() {
    this._pullToRefreshListView.beginRefresh()
  }

  componentWillUnmount() {
    clearTimeout(timer1)
    clearTimeout(timer2)
  }

  orderList(handle) {
    if (handle !== 'moreLoad') {
      this.setState({
        dataList: [],
        pageIndex: 1
      })
    }
    netservice.get(api.getBalanceOederList, {
      pageIndex: this.state.pageIndex,
      pageSize: 5,
      balanceId: this.props.balanceId
    }).then(response => {
      let newDataList = this.state.dataList.concat(response.BalanceOrders.records)
      if (newDataList.length === 0) {
        newDataList = [0]
      }
      this.setState({
        dataList: newDataList,
        dataSource: this.state.dataSource.cloneWithRows(newDataList),
        total: response.BalanceOrders.total,
        isToNextPage: true
      })
    })
  }

  _onRefresh(time) {
    //页面刷新时阻止进入下一页
    this.setState({
      isToNextPage: false
    })
    timer1 = setTimeout(() => {
      this.orderList()
      this._pullToRefreshListView.endRefresh()
    }, time ? time : 1000)
  }

  loadMore() {
    //页面刷新时阻止进入下一页
    this.setState({
      isToNextPage: false
    })
    timer2 = setTimeout(() => {
      this.setState({
        pageIndex: this.state.pageIndex + 1
      })
      let length = this.state.dataList.length
      this.orderList('moreLoad')
      let loadedAll
      if (length >= this.state.total) {
        loadedAll = true
        this._pullToRefreshListView.endLoadMore(loadedAll)
      } else {
        loadedAll = false
        this._pullToRefreshListView.endLoadMore(loadedAll)
      }
    }, 1000)
  }

  toOrderDetail(orderId) {
    if (this.state.isToNextPage) {
      this.PageUtil.jumpPageWithComponent(OrderDetail2, {orderId: orderId, status: 3, func: this._onRefresh.bind(this)})
    }
  }

  renderGList(gList) {
    if (this.state.total === 0) {
      return (<NotRecord/>)
    }
    return (
      <ListItem style={styles.listItem}>
        <Body style={{marginTop:0}}>
        <View
          style={styles.listHeader}>
          <Text
            style={{flex:1,fontSize:getSize(13),color:'#767676',marginLeft:0,}}>{gList.createTime.substring(0, 11)}</Text>
          <Text style={{color:'#767676',alignItems:'flex-end',fontSize:getSize(13)}}>订单编号:{gList.orderCode}</Text>
        </View>
        <Text
          style={{color:'#969696',marginBottom:getSize(4),marginLeft:0,fontSize:getSize(13)}}>{gList.coName}</Text>
        <TouchableWithoutFeedback onPress={(orderId)=>this.toOrderDetail(gList.id)}>
          <View
            style={{flexDirection: 'row',borderBottomColor: '#95989A',borderBottomWidth:1/3,paddingBottom:getSize(6.5)}}>
            <View style={styles.imgWrap}>
              <Image
                source={{uri:gList.spuPic+'@w_200'}}
                style={{width:getSize(72),height:getSize(72)}}
              />
            </View>
            <View style={{flex:1}}>
              <View style={{height:getSize(52)}}>
                <Text style={{color:'#95989A',fontSize:getSize(13)}}>{gList.skuName}</Text>
              </View>
              <View style={{flexDirection:'row'}}>
                <Text style={{flex:1,color:'#95989A'}}>￥{gList.salePrice}</Text>
                <Text style={{textAlign:'right',color:'#95989A'}}>数量:{gList.skuNum}</Text>
              </View>
            </View>
          </View>
        </TouchableWithoutFeedback>
        <View style={{height:getSize(41.5),alignItems:'center',flexDirection:'row'}}>
          <View style={{flex:1}}>
            <Text style={{color:'#95989A',marginLeft:0,}}>合计金额：<Text
              style={{color:'#E51C23'}}>{gList.originalPay}</Text></Text>
          </View>
        </View>
        </Body>
      </ListItem>

    );
  }

  _renderHeader = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {refresh_none, refresh_idle, will_refresh, refreshing,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch (pullState) {
      case refresh_none:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>刷新结束</Text>
          </View>
        )
      case refresh_idle:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>下拉刷新{pullDistancePercent}%</Text>
          </View>
        )
      case will_refresh:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>刷新释放{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case refreshing:
        return (
          <View
            style={{flexDirection: 'row', height: 50, justifyContent: 'center', alignItems: 'center'}}>
            {this._renderActivityIndicator()}<Text>刷新中……</Text>
          </View>
        )
    }
  }

  _renderActivityIndicator() {
    return ActivityIndicator ? (
        <ActivityIndicator
          style={{marginRight: 10,}}
          animating={true}
          color={'#ff0000'}
          size={'small'}/>
      ) : Platform.OS == 'android' ?
        (
          <ProgressBarAndroid
            style={{marginRight: 10,}}
            color={'#ff0000'}
            styleAttr={'Small'}/>

        ) : (
          <ActivityIndicatorIOS
            style={{marginRight: 10,}}
            animating={true}
            color={'#ff0000'}
            size={'small'}/>
        )
  }

  _renderFooter = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {load_more_none, load_more_idle, will_load_more, loading_more, loaded_all,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch (pullState) {
      case load_more_none:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载完成</Text>
          </View>
        )
      case load_more_idle:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载{pullDistancePercent}%</Text>
          </View>
        )
      case will_load_more:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载释放{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case loading_more:
        return (
          <View
            style={{flexDirection: 'row', height: 35, justifyContent: 'center', alignItems: 'center'}}>
            {this._renderActivityIndicator()}<Text>加载中</Text>
          </View>
        )
      case loaded_all:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>已到底部</Text>
          </View>
        )
    }
  }

  render() {
    return (
      <Container
        style={{flex:1,backgroundColor:'#F4F4F4'}}>
        <Header iosBarStyle="light-content" backgroundColor="#FF562F"
                style={{backgroundColor:'#FF562F',height:Platform.OS==='ios'?getSize(64):getSize(50),borderBottomWidth:0,marginBottom:getSize(7)}}>
          <StatusBar
            backgroundColor={'#303135'}
          />
          <Left style={{flex:1}}>
            <Button transparent onPress={this.PageUtil.pop}>
              <Icon name='arrow-back' style={{fontSize:getSize(24),color:'white'}}/>
            </Button>
          </Left>
          <Body style={{alignItems:'center'}}>
          <Title style={{color:'white',fontSize:getSize(19)}}>订单列表</Title>
          </Body>
          <Right style={{flex:1}}/>
        </Header>
        <PullToRefreshListView
          ref={ (component) => this._pullToRefreshListView = component }
          viewType={PullToRefreshListView.constants.viewType.listView}
          initialListSize={5}
          enableEmptySections={true}
          dataSource={this.state.dataSource}
          pageSize={1000}
          renderRow={(gList)=>this.renderGList(gList)}
          renderHeader={this._renderHeader}
          renderFooter={this._renderFooter}
          onRefresh={()=>this._onRefresh()}
          onLoadMore={()=>this.loadMore()}
          pullUpDistance={35}
          pullUpStayDistance={50}
          pullDownDistance={35}
          pullDownStayDistance={50}
        />
      </Container>
    );
  }
}

export default connect()(OrderList)
const styles = {
  listItem: {
    backgroundColor: 'white',
    marginLeft: 0,
    marginBottom: 9,
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 10,
    paddingRight: 10
  },
  listHeader: {
    flexDirection: 'row',
    borderBottomWidth: 1 / 3,
    height: getSize(22.5),
    alignItems: 'center',
    borderBottomColor: '#95989A',
    marginBottom: getSize(6.5)
  },
  imgWrap: {
    borderWidth: 1,
    borderColor: '#C6C6C6',
    width: getSize(80),
    height: getSize(80),
    justifyContent: 'center',
    alignItems: 'center'
  },
  btn: {
    width: getSize(65),
    height: getSize(26),
    backgroundColor: '#16BD42',
    justifyContent: 'center'
  },
  butText: {
    textAlign: 'center',
    width: getSize(65),
    fontSize: getSize(15),
    height: getSize(26),
    lineHeight: parseInt(getSize(24))
  }
};